#include "codelist.h"
#include <QDebug>

using namespace Moolink;

CodeList::CodeList(QObject *parent) :
    QAbstractListModel(parent)
{
    code_list.clear();
    m_roleNames.insert(RoleCodeId, "id");
    m_roleNames.insert(RoleCodeName, "codeName");
    m_roleNames.insert(RoledataString, "dataString");


    //从数据库初始化设备参数
//    code_list.push_back(Device("sensor01","COM10","A",1));
//    code_list.push_back(Device("sensor02","COM10","A",2));
//    code_list.push_back(Device("sensor03","COM10","A",3));
//    code_list.push_back(Device("sensor04","COM10","A",4));
//    code_list.push_back(Device("sensor05","COM10","A",5));
//    code_list.push_back(Device("sensor06","COM10","A",6));
//    code_list.push_back(Device("sensor07","COM10","A",7));

}


int CodeList::rowCount(const QModelIndex &parent) const
{
    return code_list.size();
}

int CodeList::rowCountRead()
{
    return code_list.size();
}


QVariant CodeList::data(const QModelIndex &index, int role) const
{
    Code ele = code_list.at(index.row());
    QVariant var;
    switch (role) {
//    RoleName
//    RolePortname,
//    RoleProtocol,
//    RoleCommaddr,
//    RolecolorCode
    case RoleCodeId:
        var = ele.id;
        break;
    case RoleCodeName:
        var = ele.codeName;
        break;
    case RoledataString:
        var = ele.dataString;
        break;
    default:
        break;
    }

    return var;
}


QHash<int, QByteArray> CodeList::roleNames() const
{
    return m_roleNames;
}


//int CodeList::getdataIndexById(QString codeId)
//{

//    for(int i=0;i<code_list.size();i++)
//    {

//        if(code_list[i].id==codeId) return i;
//    }

//}




void CodeList::changeDataString(int index,QString str,int error)
{
    //取出设备端口，取出设备协议，取工作任务

    //打开设备端口，根据工作任务调用协议数据生成方法指令数据，从端口发送指令

    //等待取回端口数据，根据工作任务调用协议数据分析方法返回所需要的数据

    //更新界面数据显示字串
    beginResetModel();
    if(0==error) code_list[index].colorCode="green"; else code_list[index].colorCode="red";
    code_list[index].dataString=str;
    endResetModel();
}


void CodeList::addCode(QVariant codeVar,int Dindex)
{
    beginInsertRows(QModelIndex(), code_list.count(), code_list.count());
    code_list.push_back(Code(codeVar,Dindex));
    endInsertRows();
    qDebug()<<"addCode Ok,Now ListCount="<<code_list.size();
}
